<?php

function wpf_tassonomia_registra($labels, $object_type_name,$single=false, $cap = '')
{
	$name = strtolower($labels['name']);
        
        if ($cap=='') $cap = array(
                'manage_terms' => 'manage_categories',
                'edit_terms' => 'manage_categories',
                'delete_terms' => 'manage_categories',
                'assign_terms' => 'manage_categories',
            );
        
        if ($single) $ui = 'radio';
        else         $ui = true;
	
        if (taxonomy_exists($name))
	{
		register_taxonomy_for_object_type($name, $object_type_name);
	}
	else
	{
		register_taxonomy(
				$name,
				$object_type_name,
				array(
						'hierarchical' => true,
						'labels' => $labels,
						'show_ui' => $ui,
						'query_var' => true,
                                                'capabilities' => $cap,
						'rewrite' => array(
								'slug' => $name
						)
				)
		);

		// verifico se ho già definita la tassonomia, altrimenti inserisco quelle di default
		if (!term_exists('generale', $name))
		{
			//@TODO inserire alcuni argomenti
			wpf_insert_term('Generale', // the term
					$name, // the taxonomy
					array(
							'description' => ($labels['name'] . ': nome generico. NON ELIMINARE!'),
							'slug' => 'generale',
							'parent' => ''
					)
			);
		}
	}
}

function wpf_tassonomia_registra_tipologia($object_type_name)
{
	$labels = array(
			'name' => _x('Tipologie', 'taxonomy general name' ),
			'singular_name' => _x('Tipologia', 'taxonomy singular name'),
			'search_items' =>  __('Cerca le tipologie'),
			'all_items' => __('Tutte le tipologie'),
			'parent_item' => __('Tipologia superiore'),
			'parent_item_colon' => __('Tipologia superiore:'),
			'edit_item' => __('Modifica tipologia'),
			'update_item' => __('Aggiorna tipologia'),
			'add_new_item' => __('Aggiungi nuova tipologia'),
			'new_item_name' => __('Nome tipologia'),
			'menu_name' => __('Tipologia')
	);
        $cap = array(
                'manage_terms' => 'administrator',
                'edit_terms' => 'administrator',
                'delete_terms' => 'administrator',
                'assign_terms' => 'edit_risorse',
            
        );
	wpf_tassonomia_registra($labels, $object_type_name,true,$cap);
	
	if (!term_exists( 'docente', 'tipo')) {
        admin_insert_term('Docente', 'tipo', array('description'=> 'Risorsa umana con ruolo di docente'));
        admin_insert_term('Fornitore', 'tipo', array('description'=> 'Fornitore di servizi'));
        admin_insert_term('Aula', 'tipo', array('description'=> 'Aula in cui svolgere i corsi'));
        admin_insert_term('Segretaria', 'tipo', array('description'=> 'Risorsa umana con ruolo di segretaria'));
  }
}

function wpf_tassonomia_page_tipologia() {
     wp_redirect('edit-tags.php?taxonomy=tipologie&post_type=wpf_risorsa');
     exit();
 }

function wpf_tassonomia_registra_competenza($object_type_name)
{
	$labels = array(
			'name' => _x('Competenze', 'taxonomy general name' ),
			'singular_name' => _x('Competenza', 'taxonomy singular name'),
			'search_items' =>  __('Cerca le competenze'),
			'all_items' => __('Tutte le competenze'),
			'parent_item' => __('Competenza superiore'),
			'parent_item_colon' => __('Competenza superiore:'),
			'edit_item' => __('Modifica competenza'),
			'update_item' => __('Aggiorna competenza'),
			'add_new_item' => __('Aggiungi nuova competenza'),
			'new_item_name' => __('Nome competenza'),
			'menu_name' => __('Competenza')
	);

	wpf_tassonomia_registra($labels, $object_type_name);
	
	if (!term_exists( 'informatica', 'competenza')) {
        admin_insert_term('Informatica', 'competenza', array('description'=> 'Competenze in informatica'));
        admin_insert_term('AAA', 'competenza', array('description'=> 'aaa'));
        admin_insert_term('BBB', 'competenza', array('description'=> 'bbb'));
        admin_insert_term('CCC', 'competenza', array('description'=> 'ccc'));
  }
}

function wpf_tassonomia_page_competenza() {
     wp_redirect('edit-tags.php?taxonomy=competenze&post_type=wpf_risorse');
     exit();
 }

function wpf_tassonomia_registra_classificazione($object_type_name)
{
	$labels = array(
			'name' => _x('Classificazioni', 'taxonomy general name' ),
			'singular_name' => _x('Classificazione', 'taxonomy singular name'),
			'search_items' =>  __('Cerca le classificazioni'),
			'all_items' => __('Tutte le classificazioni'),
			'parent_item' => __('Classificazione superiore'),
			'parent_item_colon' => __('Classificazione superiore:'),
			'edit_item' => __('Modifica classificazione'),
			'update_item' => __('Aggiorna classificazione'),
			'add_new_item' => __('Aggiungi nuova classificazione'),
			'new_item_name' => __('Nome classificazione'),
			'menu_name' => __('Classificazione')
	);

	wpf_tassonomia_registra($labels, $object_type_name);
}

function wpf_tassonomia_page_classificazione() {
     wp_redirect('edit-tags.php?taxonomy=classificazioni&post_type=wpf_progetto');
     exit();
 }

function wpf_tassonomia_registra_argomento($object_type_name)
{
	$labels = array(
			'name' => _x('Argomenti', 'taxonomy general name' ),
			'singular_name' => _x('Argomento', 'taxonomy singular name'),
			'search_items' =>  __('Cerca gli argomenti'),
			'all_items' => __('Tutti gli argomenti'),
			'parent_item' => __('Argomento superiore'),
			'parent_item_colon' => __('Argomento superiore:'),
			'edit_item' => __('Modifica argomento'),
			'update_item' => __('Aggiorna argomento'),
			'add_new_item' => __('Aggiungi nuovo argomento'),
			'new_item_name' => __('Nome argomento'),
			'menu_name' => __('Argomento')
	);
        

	wpf_tassonomia_registra($labels, $object_type_name);
}

function wpf_tassonomia_page_argomento() {
     wp_redirect('edit-tags.php?taxonomy=argomenti&post_type=wpf_modulo');
     exit();
 }


function wpf_tassonomia_registra_partner($object_type_name)
{
	$labels = array(
			'name' => _x('Partners', 'taxonomy general name' ),
			'singular_name' => _x('Partner', 'taxonomy singular name'),
			'search_items' =>  __('Cerca i partners'),
			'all_items' => __('Tutti i partners'),
			'parent_item' => __('Partner superiore'),
			'parent_item_colon' => __('Partner superiore:'),
			'edit_item' => __('Modifica partner'),
			'update_item' => __('Aggiorna partner'),
			'add_new_item' => __('Aggiungi nuovo partner'),
			'new_item_name' => __('Nome partner'),
			'menu_name' => __('Partner')
	);

	wpf_tassonomia_registra($labels, $object_type_name);
}

function wpf_tassonomia_page_partner() {
     wp_redirect('edit-tags.php?taxonomy=partners&post_type=wpf_progetto');
     exit();
 }

function wpf_tassonomia_registra_macrovoce($object_type_name)
{
	$labels = array(
			'name' => _x('Macrovoci', 'taxonomy general name' ),
			'singular_name' => _x('Macrovoce', 'taxonomy singular name'),
			'search_items' =>  __('Cerca le macrovoci'),
			'all_items' => __('Tutte le macrovoci'),
			'parent_item' => __('Macrovoce superiore'),
			'parent_item_colon' => __('Macrovoce superiore:'),
			'edit_item' => __('Modifica macrovoce'),
			'update_item' => __('Aggiorna macrovoce'),
			'add_new_item' => __('Aggiungi nuova macrovoce'),
			'new_item_name' => __('Nome macrovoce'),
			'menu_name' => __('Macrovoce')
	);

	wpf_tassonomia_registra($labels, $object_type_name);
}

/*
The class constants are 
  - taxonomy: the taxonomy slug
  - taxonomy_metabox_id: the ID of the original taxonomy metabox
  - post type - the post type the metabox appears on
*/

class WordPress_Radio_Taxonomy {
	static $taxonomy = 'mytaxonomy';
	static $taxonomy_metabox_id = 'mytaxonomydiv';
	static $post_type= 'post';

	public function load(){
		//Remove old taxonomy meta box  
		add_action( 'admin_menu', array(__CLASS__,'remove_meta_box'));  

		//Add new taxonomy meta box  
		add_action( 'add_meta_boxes', array(__CLASS__,'add_meta_box'));  

		//Load admin scripts
		add_action('admin_enqueue_scripts',array(__CLASS__,'admin_script'));

		//Load admin scripts
		add_action('wp_ajax_radio_tax_add_taxterm',array(__CLASS__,'ajax_add_term'));
	}


	public static function remove_meta_box(){  
   		remove_meta_box(static::$taxonomy_metabox_id, static::$post_type, 'normal');  
	} 


	public function add_meta_box() {  
		add_meta_box( 'mytaxonomy_id', 'My Radio Taxonomy',array(__CLASS__,'metabox'), static::$post_type ,'side','core');  
	}  
        

	//Callback to set up the metabox  
	public static function metabox( $post ) {  
		//Get taxonomy and terms  
       	 $taxonomy = self::$taxonomy;
      
       	 //Set up the taxonomy object and get terms  
       	 $tax = get_taxonomy($taxonomy);  
       	 $terms = get_terms($taxonomy,array('hide_empty' => 0));  
      
       	 //Name of the form  
       	 $name = 'tax_input[' . $taxonomy . ']';  
      
       	 //Get current and popular terms  
       	 $popular = get_terms( $taxonomy, array( 'orderby' => 'count', 'order' => 'DESC', 'number' => 10, 'hierarchical' => false ) );  
       	 $postterms = get_the_terms( $post->ID,$taxonomy );  
       	 $current = ($postterms ? array_pop($postterms) : false);  
       	 $current = ($current ? $current->term_id : 0);  
       	 ?>  
      
		<div id="taxonomy-<?php echo $taxonomy; ?>" class="categorydiv">
			<!-- Display tabs-->
			<ul id="<?php echo $taxonomy; ?>-tabs" class="category-tabs">
				<li class="tabs"><a href="#<?php echo $taxonomy; ?>-all" tabindex="3"><?php echo $tax->labels->all_items; ?></a></li>
				<li class="hide-if-no-js"><a href="#<?php echo $taxonomy; ?>-pop" tabindex="3"><?php _e( 'Most Used' ); ?></a></li>
			</ul>

			<!-- Display taxonomy terms -->
			<div id="<?php echo $taxonomy; ?>-all" class="tabs-panel">
				<ul id="<?php echo $taxonomy; ?>checklist" class="list:<?php echo $taxonomy?> categorychecklist form-no-clear">
				<?php foreach($terms as $term){
       				 $id = $taxonomy.'-'.$term->term_id;
					$value= (is_taxonomy_hierarchical($taxonomy) ? "value='{$term->term_id}'" : "value='{$term->term_slug}'");
				        echo "<li id='$id'><label class='selectit'>";
				        echo "<input type='radio' id='in-$id' name='{$name}'".checked($current,$term->term_id,false)." {$value} />$term->name<br />";
				        echo "</label></li>";
		       	 }?>
				</ul>
			</div>

			<!-- Display popular taxonomy terms -->
			<div id="<?php echo $taxonomy; ?>-pop" class="tabs-panel" style="display: none;">
				<ul id="<?php echo $taxonomy; ?>checklist-pop" class="categorychecklist form-no-clear" >
				<?php foreach($popular as $term){
				        $id = 'popular-'.$taxonomy.'-'.$term->term_id;
					$value= (is_taxonomy_hierarchical($taxonomy) ? "value='{$term->term_id}'" : "value='{$term->term_slug}'");
				        echo "<li id='$id'><label class='selectit'>";
				        echo "<input type='radio' id='in-$id'".checked($current,$term->term_id,false)." {$value} />$term->name<br />";
				        echo "</label></li>";
				}?>
				</ul>
			</div>

			 <p id="<?php echo $taxonomy; ?>-add" class="">
				<label class="screen-reader-text" for="new<?php echo $taxonomy; ?>"><?php echo $tax->labels->add_new_item; ?></label>
				<input type="text" name="new<?php echo $taxonomy; ?>" id="new<?php echo $taxonomy; ?>" class="form-required form-input-tip" value="<?php echo esc_attr( $tax->labels->new_item_name ); ?>" tabindex="3" aria-required="true"/>
				<input type="button" id="" class="radio-tax-add button" value="<?php echo esc_attr( $tax->labels->add_new_item ); ?>" tabindex="3" />
				<?php wp_nonce_field( 'radio-tax-add-'.$taxonomy, '_wpnonce_radio-add-tag', false ); ?>
			</p>
		</div>
        <?php  
    }

	 public function admin_script(){
		wp_register_script( 'radiotax', dirname(__FILE__) . '/js/radiotax.js', array('jquery'), null, true ); // We specify true here to tell WordPress this script needs to be loaded in the footer  
		wp_localize_script( 'radiotax', 'radio_tax', array('slug'=>self::$taxonomy));
		wp_enqueue_script( 'radiotax' );  
	}

	public function ajax_add_term(){

		$taxonomy = !empty($_POST['taxonomy']) ? $_POST['taxonomy'] : '';
		$term = !empty($_POST['term']) ? $_POST['term'] : '';
		$tax = get_taxonomy($taxonomy);

		check_ajax_referer('radio-tax-add-'.$taxonomy, '_wpnonce_radio-add-tag');

		if(!$tax || empty($term))
			exit();

		if ( !current_user_can( $tax->cap->edit_terms ) )
			die('-1');

		$tag = wp_insert_term($term, $taxonomy);

		if ( !$tag || is_wp_error($tag) || (!$tag = get_term( $tag['term_id'], $taxonomy )) ) {
			//TODO Error handling
			exit();
		}
	
		$id = $taxonomy.'-'.$tag->term_id;
		$name = 'tax_input[' . $taxonomy . ']';
		$value= (is_taxonomy_hierarchical($taxonomy) ? "value='{$tag->term_id}'" : "value='{$term->tag_slug}'");

		$html ='<li id="'.$id.'"><label class="selectit"><input type="radio" id="in-'.$id.'" name="'.$name.'" '.$value.' />'. $tag->name.'</label></li>';
	
		echo json_encode(array('term'=>$tag->term_id,'html'=>$html));
		exit();
	}

}

function wpf_tassonomia_page_macrovoce() {
     wp_redirect('edit-tags.php?taxonomy=macrovoci&post_type=wpf_progetto');
     exit();
 }

 WordPress_Radio_Taxonomy::load();

?>
